/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.z100h.supplychain.statistics.web;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.z100h.supplychain.statistics.entity.StatSkuInDetailMonthly;
import com.z100h.supplychain.statistics.entity.StatSkuOutDetailMonthly;
import com.z100h.supplychain.statistics.entity.StatTaskMonthly;
import com.z100h.supplychain.statistics.service.StatSkuInDetailMonthlyService;
import com.z100h.supplychain.statistics.service.StatSkuOutDetailMonthlyService;
import com.z100h.supplychain.statistics.service.StatTaskMonthlyService;

/**
 * 月度统计报表Controller
 * @author fyh
 * @version 2019-03-06
 */
@Controller
@RequestMapping(value = "${adminPath}/sc/stattaskmonthly/statTaskMonthly")
public class StatTaskMonthlyController extends BaseController {

	@Autowired
	private StatTaskMonthlyService statTaskMonthlyService;
	
	@Autowired
	private StatSkuOutDetailMonthlyService statSkuOutDetailMonthlyService;
	
	@Autowired
	private StatSkuInDetailMonthlyService statSkuInDetailMonthlyService;
	
	@ModelAttribute
	public StatTaskMonthly get(@RequestParam(required=false) String id) {
		StatTaskMonthly entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = statTaskMonthlyService.get(id);
		}
		if (entity == null){
			entity = new StatTaskMonthly();
		}
		return entity;
	}
	
	/**
	 * 月度统计报表列表页面
	 */
	@RequiresPermissions("sc:stattaskmonthly:statTaskMonthly:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "supplychain/statistics/statTaskMonthlyList";
	}
	
		/**
	 * 月度统计报表列表数据
	 */
	@ResponseBody
	@RequiresPermissions("sc:stattaskmonthly:statTaskMonthly:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(StatTaskMonthly statTaskMonthly, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<StatTaskMonthly> page = statTaskMonthlyService.findPage(new Page<StatTaskMonthly>(request, response), statTaskMonthly); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑月度统计报表表单页面
	 */
	@RequiresPermissions(value={"sc:stattaskmonthly:statTaskMonthly:view","sc:stattaskmonthly:statTaskMonthly:add","sc:stattaskmonthly:statTaskMonthly:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(StatTaskMonthly statTaskMonthly, Model model) {
		model.addAttribute("statTaskMonthly", statTaskMonthly);
		if(StringUtils.isBlank(statTaskMonthly.getId())){//如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		return "modules/sc/stattaskmonthly/statTaskMonthlyForm";
	}

	/**
	 * 保存月度统计报表
	 */
	@RequiresPermissions(value={"sc:stattaskmonthly:statTaskMonthly:add","sc:stattaskmonthly:statTaskMonthly:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(StatTaskMonthly statTaskMonthly, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, statTaskMonthly)){
			return form(statTaskMonthly, model);
		}
		//新增或编辑表单保存
		statTaskMonthlyService.save(statTaskMonthly);//保存
		addMessage(redirectAttributes, "保存月度统计报表成功");
		return "redirect:"+Global.getAdminPath()+"/sc/stattaskmonthly/statTaskMonthly/?repage";
	}
	
	/**
	 * 删除月度统计报表
	 */
	@ResponseBody
	@RequiresPermissions("sc:stattaskmonthly:statTaskMonthly:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(StatTaskMonthly statTaskMonthly, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		statTaskMonthlyService.delete(statTaskMonthly);
		j.setMsg("删除月度统计报表成功");
		return j;
	}
	
	/**
	 * 批量删除月度统计报表
	 */
	@ResponseBody
	@RequiresPermissions("sc:stattaskmonthly:statTaskMonthly:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			statTaskMonthlyService.delete(statTaskMonthlyService.get(id));
		}
		j.setMsg("删除月度统计报表成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("sc:stattaskmonthly:statTaskMonthly:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(StatTaskMonthly statTaskMonthly, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "月度统计报表"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<StatTaskMonthly> page = statTaskMonthlyService.findPage(new Page<StatTaskMonthly>(request, response, -1), statTaskMonthly);
    		new ExportExcel("月度统计报表", StatTaskMonthly.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出月度统计报表记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("sc:stattaskmonthly:statTaskMonthly:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<StatTaskMonthly> list = ei.getDataList(StatTaskMonthly.class);
			for (StatTaskMonthly statTaskMonthly : list){
				try{
					statTaskMonthlyService.save(statTaskMonthly);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条月度统计报表记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条月度统计报表记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入月度统计报表失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/sc/stattaskmonthly/statTaskMonthly/?repage";
    }
	
	/**
	 * 下载导入月度统计报表数据模板
	 */
	@RequiresPermissions("sc:stattaskmonthly:statTaskMonthly:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "月度统计报表数据导入模板.xlsx";
    		List<StatTaskMonthly> list = Lists.newArrayList(); 
    		new ExportExcel("月度统计报表数据", StatTaskMonthly.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/sc/stattaskmonthly/statTaskMonthly/?repage";
    }
	
	
	/**
	 * 
	 * 跳转出库详情
	 * 
	 * @param request
	 * @return
	 * @author: Fyh - 1009173473@qq.com 
	 * @date: Created on 2019年3月12日 下午2:05:01
	 */
	@RequestMapping(value ="monthlyStockoutDetail")
	public String monthlyStockoutDetail(HttpServletRequest request) {
		String id =request.getParameter("id");
		List<StatSkuOutDetailMonthly> list=statSkuOutDetailMonthlyService.get(id);
		StatTaskMonthly taskMonthly=statTaskMonthlyService.get(id);
		request.setAttribute("taskMonth", taskMonthly.getTaskMonth());
		request.setAttribute("list", list);
		return "supplychain/statistics/monthlyStockoutDetail";
	}
	
	/**
	 * 
	 * 跳转入库详情
	 * 
	 * @param request
	 * @return
	 * @author: Fyh - 1009173473@qq.com 
	 * @date: Created on 2019年3月12日 下午2:05:17
	 */
	@RequestMapping(value = "monthlyStockinDetail")
	public String monthlyStockinDetail(HttpServletRequest request) {
		String id =request.getParameter("id");
		List<StatSkuInDetailMonthly> list=statSkuInDetailMonthlyService.get(id);
		StatTaskMonthly taskMonthly=statTaskMonthlyService.get(id);
		request.setAttribute("taskMonth", taskMonthly.getTaskMonth());
		request.setAttribute("list", list);
		return "supplychain/statistics/monthlyStockinDetail";
	}

	@RequestMapping(value = "exportMonthlyStockoutDetail")
	public void exportMonthlyStockoutDetail(HttpServletRequest request,HttpServletResponse response) {
		String id =request.getParameter("id");
		try {
			Workbook workbook = statSkuOutDetailMonthlyService.createWorkbook(id);
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + new Date().getTime()+".xls");
			workbook.write(response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "exportMonthlyStockinDetail")
	public void exportMonthlyStockinDetail(HttpServletRequest request,HttpServletResponse response) {
		String id =request.getParameter("id");
		try {
			Workbook workbook = statSkuInDetailMonthlyService.createWorkbook(id);
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + new Date().getTime()+".xls");
			workbook.write(response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}